package com.kaibes.orm.spring.jdbc;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;

import com.kaibes.orm.core.core.Mapper;
import com.kaibes.orm.core.core.SqlRunner;
import com.kaibes.orm.core.core.TableService;
import com.kaibes.orm.core.dialect.Dialect;
import com.kaibes.orm.core.listener.CacheListener;

public class TableServiceImpl<E> implements TableService<E>, InitializingBean {

    @Autowired(required = false)
    protected Mapper<E> mapper;
    @Autowired
    private SqlRunner sqlRunner;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private Dialect dialect;
    @Autowired(required = false)
    protected CacheListener<E> cacheListener;

    @Override
    public Mapper<E> getMapper() {
        return mapper;
    }

	@Override
	public void afterPropertiesSet() throws Exception {
		if (mapper == null) {
            mapper = new BaseMapper<>(dialect, sqlRunner, transactionManager, transactionDefinition);
            initMapper();
        }
        if (cacheListener != null) {
            mapper.setCacheListener(cacheListener);
        }
	}
    
}
